<?php

namespace Admin\Api\Controllers;

use Admin\Models\device\XhsysUsertablet;
use Admin\Models\hrm\XhhrmExperience;
use Admin\Models\hrm\XhhrmResource;
use Admin\Models\hrm\XhhrmStaffContact;
use Admin\Models\ims\XHImsApplyTablet;
use Admin\Models\ims\XHImsProduce;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\sys\XhsysUserTch;
use Admin\Models\user\XhsysUser;
use Helpers\Main;
use Helpers\Tool;
use Helpers\User;
use Modules\Ims;
use Phalcon\Paginator\Adapter\QueryBuilder;

class UserController extends ControllerBase
{

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170830
     * modify by ck 20170927
     *
     * @SWG\Get(
     *     path="/api/user/users",
     *     tags={"User"},
     *     summary="搜索用户(分页)",
     *     description="返回id，姓名，电话信息",
     *     @SWG\Parameter(name="userType", in="query", description="用户类型", type="integer"),
     *     @SWG\Parameter(name="schoolId", in="query", description="学校id", type="integer"),
     *     @SWG\Parameter(name="keyword", in="query", description="搜索词", type="string"),
     *     @SWG\Parameter(name="adClsName", in="query", description="行政班", type="string"),
     *     @SWG\Parameter(name="ignoreHistory", in="query", description="忽略历史", type="boolean", default="true"),
     *     @SWG\Parameter(name="ignoreDisable", in="query", description="忽略禁用", type="boolean", default="true"),
     *     @SWG\Parameter(name="item", in="query", description="搜索项", type="string", enum={"logonName", "userName"}),
     *     @SWG\Parameter(name="keywords", in="query", description="批量搜索内容(逗号间隔)", type="string"),
     *     @SWG\Parameter(name="page", in="query", description="页码", type="integer", default="1"),
     *     @SWG\Parameter(name="size", in="query", description="行数", type="integer", default="50"),
     *     @SWG\Response(response="200", description="获取列表成功",
     *         @SWG\Schema(
     *             type="array",
     *             @SWG\Items(ref="#/definitions/UserInfo")
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function usersAction()
    {
        if (!$this->request->isGet()) {
            return $this->sendErrorResponse(400, '请求方式不正确');
        }
        $itemEnum   = [
            'logonName' => 'sLogonName',
            'userName'  => 'sUserName',
        ];
        $userType       = $this->request->getQuery('userType', 'int');
        $schoolId       = $this->request->getQuery('schoolId', 'int');
        $keyword        = $this->request->getQuery('keyword', 'string');
        $adClsName      = $this->request->getQuery('adClsName', 'string');
        $item           = $this->request->getQuery('item', 'string');
        $keywords       = $this->request->getQuery('keywords', 'string');
        $ignoreHistory  = $this->request->getQuery('ignoreHistory', 'string', 'true') == 'true';
        $ignoreDisable  = $this->request->getQuery('ignoreDisable', 'string', 'true') == 'true';
        if (in_array($userType, [6, 8])) {
            return $this->sendErrorResponse(400, '用户类型不正确');
        }
        $keywords   = explode(',', $keywords);
        try {
            $builder = $this->modelsManager->createBuilder()
                ->columns([
                    'iUserId AS userId',
                    'sUserName AS userName',
                    'sLogonName AS logonName',
                    'iSchoolId AS schoolId',
                    'sAdClsName AS adClaName',
                    'sSelfPhone AS phoneNum'
                ])
                ->from('Admin\\Models\\user\\XhsysUser')
//                ->where('bCompany = 0 AND bDelete = 0 AND bDisable = 0 AND bHistory = 0');
                ->where('bDelete = 0');
            if ($ignoreHistory) {
                $builder->andWhere('bHistory = 0');
            }
            if ($ignoreDisable) {
                $builder->andWhere('bDisable = 0');
            }
            if ($userType) {
                $builder->andWhere('iUserType = :userType:', ['userType' => $userType]);
            }
            if ($schoolId) {
                $builder->andWhere('iSchoolId = :schoolId:', ['schoolId' => $schoolId]);
            }
            if ($keyword) {
                $builder->andWhere(
                    'sUserName LIKE :keyword: OR sLogonName LIKE :keyword:',
                    ['keyword' => "%{$keyword}%"]
                );
            }
            if ($adClsName) {
                $builder->andWhere('sAdClsName = :adClsName:', ['adClsName' => $adClsName]);
            }
            if ($item && $keywords) {
                if (!in_array($item, ['logonName', 'userName'])) {
                    return $this->sendErrorResponse(400, '搜索项不正确');
                }
                $builder->andWhere($itemEnum[$item] . ' IN ({keywords:array})', ['keywords' => $keywords]);
            }
            $paginate = new QueryBuilder([
                'builder'   => $builder,
                'limit'     => $this->request->getQuery('size', 'int', 50),
                'page'      => $this->request->getQuery('page', 'int', 1),
            ]);
            $result = $paginate->getPaginate();
            $data   = [
                'page'      => $result->current,
                'size'      => $result->limit,
                'totalPage' => $result->total_pages,
                'total'     => $result->total_items,
                'rows'      => $result->items->toArray()
            ];
            return $this->response->setJsonContent($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '获取失败！', $e->getMessage());
        }
    }


    /**
     * 注册用户
     *
     * @param string $role
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180427
     */
    public function registerAction($role = '')
    {
        if (!$this->request->isPost()) {
            return $this->sendErrorResponse(400, '请求方式不正确');
        }
        $request = $this->request->getJsonRawBody(true);
        if (!Tool::getValue($request, 'password')) {
            return $this->sendErrorResponse(400, '密码不能为空');
        }
        try {
            switch ($role) {
                case 'parents':
                    $userId = $this->registerParents($request);
                    break;
                case 'student':
                    $userId = $this->registerStudent($request);
                    break;
                default:
                    throw new \Exception('不支持该注册类型', 400);
            }
            $this->response->setHeader('user-id', $userId);
            return $this->sendSuccessResponse('注册成功', true, 201);
        } catch (\Exception $e) {
            return $this->sendErrorResponse($e->getCode() ?: 500, $e->getMessage());
        }
    }

    /**
     * @param $request
     * @return string
     * @throws \Exception
     *
     * create by ck 20180427
     *
     * @SWG\Post(
     *     path="/api/user/register/parents",
     *     tags={"User"},
     *     consumes={"application/json"},
     *     summary="注册家长",
     *     description="注册家长用户",
     *     @SWG\Parameter(name="body", in="body", description="信息", required=true,
     *         @SWG\Schema(
     *              required={"phone", "password", "validCode"},
     *              @SWG\Property(property="phone", description="手机号", type="string"),
     *              @SWG\Property(property="password", description="密码", type="string"),
     *              @SWG\Property(property="validCode", description="验证码", type="string"),
     *         )
     *     ),
     *     @SWG\Response(response=201, description="成功",
     *         @SWG\Header(header="user-id", description="注册用户id", type="integer"),
     *         @SWG\Schema(
     *             required={"code", "msg"},
     *             @SWG\Property(property="code", description="状态码", type="integer"),
     *             @SWG\Property(property="msg", description="注册成功", type="string"),
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    private function registerParents($request)
    {
        if (!$request['phone']) {
            throw new \Exception('手机号不能为空', 400);
        }
        if (!$request['validCode']) {
            throw new \Exception('短信验证码不能为空', 400);
        }
        if (!Main::checkValidCode($request['phone'], $request['validCode'])) {
            throw new \Exception('短信验证码不正确', 400);
        }
        $user = new XhsysUser();
        $user->iUserType  = 5;
        $user->sLogonName = $request['phone'];
        $user->sSelfPhone = $request['phone'];
        $user->sLogonPwd  = strtoupper(md5($request['password']));
        $user->sSource    = 'register';
        if (!$user->insertAfterOld()) {
            throw new \Exception($user->getError());
        }
        return $user->iUserId;
    }

    /**
     * @param $request
     * @return string
     * @throws \Exception
     *
     * create by ck 20180427
     *
     * @SWG\Post(
     *     path="/api/user/register/student",
     *     tags={"User"},
     *     consumes={"application/json"},
     *     summary="注册学生",
     *     description="注册学生用户",
     *     @SWG\Parameter(name="body", in="body", description="信息", required=true,
     *         @SWG\Schema(
     *              required={"userName", "password", "identityCode"},
     *              @SWG\Property(property="userName", description="姓名", type="string"),
     *              @SWG\Property(property="identityCode", description="身份证号", type="string"),
     *              @SWG\Property(property="password", description="密码", type="string"),
     *              @SWG\Property(property="schoolId", description="学校id", type="integer"),
     *              @SWG\Property(property="className", description="班级名称", type="string"),
     *              @SWG\Property(property="gradeCode", description="年级", type="integer",
     *                  items={"21": "初一", "22": "初二", "23": "初三"}),
     *              @SWG\Property(property="userSex", description="性别", type="integer", items={"1": "男", "2": "女"}),
     *         )
     *     ),
     *     @SWG\Response(response=201, description="成功",
     *         @SWG\Header(header="user-id", description="注册用户id", type="integer"),
     *         @SWG\Schema(
     *             required={"code", "msg"},
     *             @SWG\Property(property="code", description="状态码", type="integer"),
     *             @SWG\Property(property="msg", description="注册成功", type="string"),
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    private function registerStudent($request)
    {
        if (!$request['userName']) {
            throw new \Exception('姓名不能为空', 400);
        }
        if (!$request['identityCode']) {
            throw new \Exception('身份证号不能为空', 400);
        }
        $user = new XhsysUser();
        $user->iUserType    = 1;
        $user->sUserName    = $request['userName'];
        $user->sLogonName   = $request['identityCode'];
        $user->sIdentityCode= $request['identityCode'];
        $user->sLogonPwd    = strtoupper(md5($request['password']));
        $user->sSource      = 'register';
        Tool::getValue($request, 'schoolId')
            and $user->iSchoolId = $request['schoolId'];
        Tool::getValue($request, 'className')
            and $user->sAdClsName = $request['className'];
        Tool::getValue($request, 'gradeCode') && is_numeric($request['gradeCode'])
            and $user->iGradeCode = $request['gradeCode'];
        Tool::getValue($request, 'userSex') && in_array($request['userSex'], [1, 2])
            and $user->iUserSex = $request['userSex'];
        if (!$user->insertAfterOld()) {
            throw new \Exception($user->getError());
        }
        return $user->iUserId;
    }

    /**
     * 重置密码
     *
     * @param string $type
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180502
     */
    public function passwordAction($type = '')
    {
        if (!$this->request->isPatch()) {
            return $this->sendErrorResponse(400, '请求方式不正确');
        }
        $request = $this->request->getJsonRawBody(true);
        if (!Tool::getValue($request, 'password')) {
            return $this->sendErrorResponse(400, '密码不能为空');
        }
        try {
            switch ($type) {
                case 'phone':
                    $this->resetPwdByPhone($request);
                    break;
                case 'old' :
                    $this->resetPwdByOld($request);
                    break;
                default:
                    throw new \Exception('不支持该方式', 400);
            }
            return $this->sendSuccessResponse('修改成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse($e->getCode() ?: 500, $e->getMessage());
        }
    }

    /**
     * @param $request
     * @throws \Exception
     *
     * create by ck 20180502
     *
     * @SWG\Patch(
     *     path="/api/user/password/phone",
     *     tags={"User"},
     *     consumes={"application/json"},
     *     summary="根据手机号重置密码",
     *     @SWG\Parameter(name="body", in="body", description="信息", required=true,
     *         @SWG\Schema(
     *              required={"phone", "password", "validCode"},
     *              @SWG\Property(property="phone", description="手机号", type="string"),
     *              @SWG\Property(property="password", description="密码(md5大写)", type="string"),
     *              @SWG\Property(property="validCode", description="验证码", type="string")
     *         )
     *     ),
     *     @SWG\Response(response="200", ref="#/responses/Success"),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    private function resetPwdByPhone($request)
    {
        if (!$request['phone']) {
            throw new \Exception('手机号不能为空', 400);
        }
        if (!$request['validCode']) {
            throw new \Exception('短信验证码不能为空', 400);
        }
        if (!Main::checkValidCode($request['phone'], $request['validCode'])) {
            throw new \Exception('短信验证码不正确', 400);
        }
        $users = XhsysUser::find([
            'conditions' => 'bDelete = 0 AND bDisable = 0 AND (sLogonName = :phone: OR sSelfPhone = :phone:)',
            'bind'       => ['phone' => $request['phone']]
        ]);
        if (count($users) < 1) {
            throw new \Exception('该手机号未注册');
        } elseif (count($users) > 1) {
            throw new \Exception('该手机号含重复记录，暂不可操作');
        } else {
            $user = $users[0];
            User::setPassword([$user->iUserId], $request['password'], true);
        }
    }

    /**
     * @param $request
     * @throws \Exception
     *
     * create by ck 20180502
     *
     * @SWG\Patch(
     *     path="/api/user/password/old",
     *     tags={"User"},
     *     consumes={"application/json"},
     *     summary="验证旧密码并修改密码",
     *     @SWG\Parameter(name="body", in="body", description="信息", required=true,
     *         @SWG\Schema(
     *              required={"userId", "password", "oldPwd"},
     *              @SWG\Property(property="userId", description="用户id", type="integer"),
     *              @SWG\Property(property="password", description="密码(md5大写)", type="string"),
     *              @SWG\Property(property="oldPwd", description="旧密码(md5大写)", type="string")
     *         )
     *     ),
     *     @SWG\Response(response="200", ref="#/responses/Success"),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    private function resetPwdByOld($request)
    {
        if (!$request['userId']) {
            throw new \Exception('用户id不能为空', 400);
        }
        if (!$request['oldPwd']) {
            throw new \Exception('旧密码不能为空', 400);
        }
        $user = XhsysUser::findFirst([
            'columns'    => 'sLogonPwd',
            'conditions' => 'bDelete = 0 AND bDisable = 0 AND bHistory = 0 AND iUserId = :userId:',
            'bind'       => ['userId' => $request['userId']]
        ]);
        if (!$user) {
            throw new \Exception('找不到该用户');
        }
        if (strtoupper($request['oldPwd']) != strtoupper($user->sLogonPwd)) {
            throw new \Exception('旧密码验证失败');
        }
        User::setPassword([$request['userId']], $request['password'], true);
    }

    /**
     * @param null $userId
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180503
     *
     * @SWG\Patch(
     *     path="/api/user/phone/{userId}",
     *     tags={"User"},
     *     consumes={"application/json"},
     *     summary="修改手机号",
     *     @SWG\Parameter(name="userId", in="query", description="用户id", required=true, type="integer"),
     *     @SWG\Parameter(name="body", in="body", description="信息", required=true,
     *         @SWG\Schema(
     *              required={"phone", "validCode"},
     *              @SWG\Property(property="phone", description="手机号", type="string"),
     *              @SWG\Property(property="validCode", description="验证码", type="string")
     *         )
     *     ),
     *     @SWG\Response(response="200", ref="#/responses/Success"),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function phoneAction($userId = null)
    {
        if (!$this->request->isPatch()) {
            return $this->sendErrorResponse(400, '请求方式不正确');
        }
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        $request = $this->request->getJsonRawBody(true);
        try {
            if (!$request['phone']) {
                throw new \Exception('手机号不能为空', 400);
            }
            if (!$request['validCode']) {
                throw new \Exception('短信验证码不能为空', 400);
            }
            if (!Main::checkValidCode($request['phone'], $request['validCode'])) {
                throw new \Exception('短信验证码不正确', 400);
            }
            $user = XhsysUser::findFirst($userId);
            if (!$user) {
                throw new \Exception('找不到该用户');
            }
            if ($request['phone'] == $user->sSelfPhone) {
                throw new \Exception('手机号一致，请检查');
            }
            $check = XhsysUser::count([
                'conditions' => 'bDelete = 0 AND (sLogonName = :phone: OR sSelfPhone = :phone:)',
                'bind'       => ['phone' => $request['phone']]
            ]);
            if ($check) {
                throw new \Exception('该手机号已被绑定');
            }
            if ($user->sLogonName == $user->sSelfPhone) {
                $user->sLogonName = $request['phone'];
            }
            $user->sSelfPhone = $request['phone'];
            if (!$user->saveWithOldData()) {
                throw new \Exception($user->getError());
            }
            return $this->sendSuccessResponse('修改成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse($e->getCode() ?: 500, $e->getMessage());
        }
    }

    /**
     * @param null $userId
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180504
     *
     * @SWG\Patch(
     *     path="/api/user/info/{userId}",
     *     tags={"User"},
     *     consumes={"application/json"},
     *     summary="修改基本信息",
     *     @SWG\Parameter(name="userId", in="query", description="用户id", required=true, type="integer"),
     *     @SWG\Parameter(name="body", in="body", description="信息", required=true,
     *         @SWG\Schema(
     *              required={},
     *              @SWG\Property(property="userName", description="姓名", type="string"),
     *              @SWG\Property(property="userSex", description="性别", type="integer", items={"1": "男", "2": "女"}),
     *              @SWG\Property(property="gradeCode", description="年级", type="integer",
     *                  items={"21": "初一", "22": "初二", "23": "初三"}),
     *              @SWG\Property(property="className", description="班级", type="string")
     *         )
     *     ),
     *     @SWG\Response(response="200", ref="#/responses/Success"),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function infoAction($userId = null)
    {
        if (!$this->request->isPatch()) {
            return $this->sendErrorResponse(400, '请求方式不正确');
        }
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        $request = $this->request->getJsonRawBody(true);
        try {
            $request = array_filter($request);
            if (!$request) {
                throw new \Exception('无变更数据');
            }
            $user = XhsysUser::findFirst($userId);
            if (!$user) {
                throw new \Exception('找不到该用户');
            }
            $fields = [
                'userName'  => 'sUserName',
                'userSex'   => 'iUserSex',
                'gradeCode' => 'iGradeCode',
                'className' => 'sAdClsName',
            ];
            foreach ($fields as $key => $field) {
                if (Tool::getValue($request, $key)) {
                    $user->$field = $request[$key];
                }
            }
            if (!$user->saveWithOldData()) {
                throw new \Exception($user->getError());
            }
            return $this->sendSuccessResponse('修改成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse($e->getCode() ?: 500, $e->getMessage());
        }
    }

    /**
     * 根据学校及学科名称获取班级
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180330
     */
    public function subjectTchAction(){
        $schoolId     = $this->request->getQuery('schoolId', 'int');
        $subjectName  = $this->request->getQuery('subjectName', 'string');
        if (!$schoolId || !$subjectName) {
            return $this->sendErrorResponse(400,'缺少参数');
        }

        $subjectEnum = XhsysEnum::getEnumByNodeName('学科');
        $flipSub     = array_flip($subjectEnum);
        if (!isset($flipSub[$subjectName])) {
            return $this->sendErrorResponse(400,'找不到学科对应的枚举');
        }

        $subject  = $flipSub[$subjectName];
        $teachers = $this->modelsManager->createBuilder()
            ->columns('u.iUserId as userId, u.SUserName as userName, t.iSubject as subject, t.iCurGrade as grade')
            ->from(['u' => '\\Admin\\Models\\user\\XhsysUser'])
            ->leftJoin('Admin\Models\sys\XhsysUserTch','u.iUserId = t.iUserId','t')
            ->where('u.iSchoolId = :schoolId: and u.iUserType = 4 ', ['schoolId' => $schoolId ])
//            ->andWhere(' u.bCompany = 0 and u.bDisable = 0 and u.bHistory = 0 and u.bDelete = 0 ')
            ->andWhere('u.bDisable = 0 and u.bHistory = 0 and u.bDelete = 0 ')
            ->andWhere('t.iSubject = :subject:',['subject' => $subject])
            ->getQuery()->execute()->toArray();

        $gradeEnum = XhsysEnum::getEnumByNodeName('年级');
        foreach ($teachers as $index => $teacher) {
            $teachers[$index]['subject'] = isset($subjectEnum[$teacher['subject']]) ? $subjectEnum[$teacher['subject']] : '' ;
            $teachers[$index]['grade']   = isset($gradeEnum[$teacher['grade']]) ? $gradeEnum[$teacher['grade']] : '' ;
        }
        return $this->sendJsonResponse($teachers);

    }


    /**
     * 根据学校id获取
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180514
     *
     */
    public function tchSubjectAction(){
        $schoolId = $this->request->getQuery('schoolId','int');
        if(!$schoolId){
            return $this->sendErrorResponse(400 , '缺少参数');
        }
        $subjectEnum = XhsysEnum::getEnumByNodeName('学科');

        $teachers = $this->modelsManager->createBuilder()
            ->columns('u.iUserId as userId, u.SUserName as userName, t.sSubjects as subjects')
            ->from(['u' => '\\Admin\\Models\\user\\XhsysUser'])
            ->leftJoin('Admin\Models\sys\XhsysUserTch','u.iUserId = t.iUserId','t')
//            ->andWhere(' u.bCompany = 0 and u.bDisable = 0 and u.bHistory = 0 and u.bDelete = 0 and u.iUserType = 4 ')
            ->andWhere('u.bDisable = 0 and u.bHistory = 0 and u.bDelete = 0 and u.iUserType = 4 ')
            ->andWhere('u.iSchoolId = :schoolId:' , ['schoolId' => $schoolId ]);
        $teachers = $teachers->getQuery()->execute()->toArray();

        foreach ($teachers as $index => &$teacher){

            if(!$teacher['subjects']){
                $teacher['subjects'] = [];
            }else{
                $teacher['subjects'] = explode(',' , $teacher['subjects']);
                foreach ($teacher['subjects'] as &$value){
                    $value = isset($subjectEnum[$value]) ? $subjectEnum[$value] : '';
                }
                unset($value);
            }
        }
        unset($teacher);

        //转化为云作业枚举
        $idByName = [
            '语文' => 1,
            '数学' => 2,
            '英语' => 3,
            '科学' => 4,
            '历史' => 5,
            '道德与法治' => 6,
            '物理' => 7,
            '化学' => 8,
            '生物' => 9,
            '地理' => 10,
            '文综' => 11,
            '理综' => 12,
            '通用技术' => 13,
            '政治' => 14,
            '信息' => 15,
            '历史' => 16
        ];

        $arr = [];
        foreach ( $subjectEnum  as $index =>$row){
            $item = [
                'value' => $idByName[$row],
                'label' => $row,
                'children' => [],
            ];
            foreach ($teachers as $teacher){
                if(in_array($row,$teacher['subjects'])){
                    $item['children'][] = ['label'=> $teacher['userName'] ,'value'=> $teacher['userId']];
                }
            }
            $arr[] = $item;
        }
        return $this->sendJsonResponse($arr);
    }





//    public function userForTypeAction($userType = null)
//    {
//        if (!$this->request->isGet()){
//            return $this->sendErrorResponse(400, '请求方式不正确！');
//        }
//        if (!in_array($userType, [1, 2, 4, 5, 9, 10])){
//            return $this->sendErrorResponse(400, '用户类型不正确！');
//        }
//        try {
//            $builder = $this->modelsManager->createBuilder()
//                ->columns(['iUserId AS userId', 'sUserName AS userName', 'sSelfPhone AS phoneNum'])
//                ->from('Admin\\Models\\user\\XhsysUser')
//                ->where('iUserType = :userType:', ['userType' => $userType]);
//            $paginate = new QueryBuilder([
//                'builder'   => $builder,
//                'limit'     => $this->request->getQuery('size', 'int', 50),
//                'page'      => $this->request->getQuery('page', 'int', 1),
//            ]);
//            $result = $paginate->getPaginate();
//            $data   = [
//                'page'      => $result->current,
//                'size'      => $result->limit,
//                'totalPage' => $result->total_pages,
//                'total'     => $result->total_items,
//                'rows'      => $result->items->toArray()
//            ];
//            return $this->response->setJsonContent($data);
//        }
//        catch(\Exception $e) {
//            return $this->sendErrorResponse(500, '获取失败！', $e->getMessage());
//        }
//    }

//    public function schoolUsersAction()
//    {
//        if (!$this->request->isGet()){
//            return $this->sendErrorResponse(400, '请求方式不正确！');
//        }
//        $schoolId = $this->request->getQuery('schoolId', 'int');
//        $userType = $this->request->getQuery('userType', 'int');
//        $keyword  = $this->request->getQuery('keyword', 'string');
//        $adClsName= $this->request->getQuery('adClsName', 'string');
//        if (!$schoolId){
//            return $this->sendErrorResponse(400, '学校id不能为空！');
//        }
//        if (!in_array($userType, [1, 4])){
//            return $this->sendErrorResponse(400, '用户类型不正确！');
//        }
//        try {
//            $builder = $this->modelsManager->createBuilder()
//                ->columns([
//                    'iUserId AS userId',
//                    'sUserName AS userName',
//                    'sLogonName AS logonName',
//                    'iSchoolId AS schoolId',
//                    'sAdClsName AS adClaName',
//                    'sSelfPhone AS phoneNum'
//                ])
//                ->from('Admin\\Models\\user\\XhsysUser')
//                ->where(
//                    'iUserType = :userType: AND iSchoolId = :schoolId:',
//                    ['userType' => $userType, 'schoolId' => $schoolId]
//                );
//            if ($keyword) {
//                $builder->andWhere(
//                    'sUserName LIKE :keyword: OR sLogonName LIKE :keyword:',
//                    ['keyword' => "%{$keyword}%"]
//                );
//            }
//            if ($adClsName) {
//                $builder->andWhere('sAdClsName = :adClsName:', ['adClsName' => $adClsName]);
//            }
//            $paginate = new QueryBuilder([
//                'builder'   => $builder,
//                'limit'     => $this->request->getQuery('size', 'int', 50),
//                'page'      => $this->request->getQuery('page', 'int', 1),
//            ]);
//            $result = $paginate->getPaginate();
//            $data   = $result->items->toArray();
//            Main::runSchoolNameByIdStr($data, ['schoolId' => 'schoolName'], true);
//            $content   = [
//                'page'      => $result->current,
//                'size'      => $result->limit,
//                'totalPage' => $result->total_pages,
//                'total'     => $result->total_items,
//                'rows'      => $data
//            ];
//            return $this->response->setJsonContent($content);
//        }
//        catch(\Exception $e) {
//            return $this->sendErrorResponse(500, '获取失败！', $e->getMessage());
//        }
//    }

    /**
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by dale  20180903
     *
     * @SWG\Post(
     *     path="/api/user/identifyTch",
     *     tags={"User"},
     *     consumes={"application/json"},
     *     summary="认证接口",
     *     description="教师认证接口",
     *     @SWG\Parameter(name="body", in="body", description="信息", required=true,
     *         @SWG\Schema(
     *              required={"tchId", "code", "devType"},
     *              @SWG\Property(property="tchId", description="教师id", type="integer"),
     *              @SWG\Property(property="devNumber", description="设备号", type="string"),
     *              @SWG\Property(property="devType", description="设备类型(中文)", type="string"),
     *              @SWG\Property(property="mac", description="mac地址", type="string"),
     *              @SWG\Property(property="imei", description="imei号", type="string"),
     *         )
     *     ),
     *     @SWG\Response(response=200, description="认证成功",
     *         @SWG\Schema(
     *             required={"code", "msg"},
     *             @SWG\Property(property="code", description="状态码", type="integer"),
     *             @SWG\Property(property="msg", description="认证成功", type="string"),
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function identifyTchAction()
    {
        try {
            $postData = $this->request->getJsonRawBody(true);
            $tchId = Tool::getValue($postData, 'tchId');
            $devNumber  = Tool::getValue($postData, 'devNumber');
            $devType = Tool::getValue($postData, 'devType');
            $mac = Tool::getValue($postData, 'mac');
            $imei = Tool::getValue($postData, 'imei');
            if (!$tchId || !$devNumber || !$devType) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $appInfo = XHImsApplyTablet::findFirst([
                'conditions' => "bDelete = 0 and iState = 3 and iSignState = 1 
                    and CONCAT(',',sTeachers,',') like :key:",
                'bind'       => ['key' => '%,'.$tchId.',%']
            ]);
            if (!$appInfo) {
                return $this->sendErrorResponse(500, '未找到需要绑定的老师信息');
            }
            $prodInfo = XHImsProduce::findFirst([
                'columns'    => 'iProdId',
                'conditions' => 'bDelete = 0 and sProdName = :sProdName:',
                'bind'       => ['sProdName' => $devType]
            ]);
            $this->db->begin();
            if (!$prodInfo) {
                throw new \Exception('未找到设备型号');
            }
            $mTchCode = $appInfo->mTchCode;
            if (!is_array($mTchCode)) {
                $mTchCode = unserialize($mTchCode) ?: [];
            }
            if (count($mTchCode) <= 0) {
                $teachers  = explode(',', $appInfo->sTeachers);
                foreach ($teachers as $teacherId) {
                    $mTchCode[$teacherId] = ['iProdId' => '', 'code' => ''];
                }
                $mTchCode[$tchId] = ['iProdId' => $prodInfo->iProdId, 'code' => $devNumber ];
            } else {
                if (isset($mTchCode[$tchId]) && $mTchCode[$tchId]['code']) {
                    throw new \Exception('该老师已被认证');
                }
                $mTchCode[$tchId] = ['iProdId' => $prodInfo->iProdId, 'code' => $devNumber ];
            }
            $appInfo->mTchCode = $mTchCode;
            if (!$appInfo->save()) {
                throw new \Exception('认证信息保存失败');
            }
            $user = XhsysUser::findFirst([
                'columns'    => 'sUserName,sSelfPhone,sLogonName,iSchoolId',
                'conditions' => 'iUserId = :tchId: and bDelete = 0',
                'bind'       => ['tchId' => $tchId]
            ]);
            if (!$user) {
                throw new \Exception('未找到该教师id对应的教师');
            }
            $checkTab = XhsysUsertablet::findFirst([
                'conditions' => ' sDevNumber = :sDevNumber: ',
                'bind'       => ['sDevNumber' => $devNumber],
                'order'      => 'iUTId desc',
            ]);
            if ($checkTab && !$checkTab->bDelete) {
                if ($checkTab->sDevNumber == $devNumber && $checkTab->sReceiverAccount == $user->sLogonName
                    && $checkTab->iReceiveStatus == 2  && $checkTab->iReceivePurpose == 3) { //已领取 教师机
                    $this->db->commit();
                    return $this->sendSuccessResponse('认证成功');
                }
                if ($checkTab->iReceiveStatus != 3) {
                    throw new \Exception('设备号为：'.$devNumber.'的设备未归还无法申请');
                }
            }
            $tablet = new XhsysUsertablet();
            $tablet->sReceiverName    = $user->sUserName;
            $tablet->sReceiverPhone   = $user->sSelfPhone;
            $tablet->sReceiverAccount = $user->sLogonName;
            $tablet->iReceiveStatus   = 2;
            $tablet->iReceivePurpose  = 3;
            $tablet->iSchoolId        = $user->iSchoolId;
            $tablet->sDevNumber       = $devNumber;
            $tablet->sDevType         = $devType;
            $tablet->iSource = 0; //自动
            if ($mac) {
                $tablet->sMacAddress = $mac;
            }
            if ($imei) {
                $tablet->sIMei = $imei;
            }
            $tablet->tReceiveTime = date('Y-m-d H:i:s', time());
            $tablet->iApTabId = $appInfo->iRTId; //授权列表 添加 申领id
            if (!$tablet->save()) {
                throw new \Exception('记录保存失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('认证成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by dale  20180903
     *
     * @SWG\Post(
     *     path="/api/user/identifyDemo",
     *     tags={"User"},
     *     consumes={"application/json"},
     *     summary="认证接口",
     *     description="演示机认证接口",
     *     @SWG\Parameter(name="body", in="body", description="信息", required=true,
     *         @SWG\Schema(
     *              required={"authCode", "code", "devType"},
     *              @SWG\Property(property="authCode", description="归还列表", type="string"),
     *              @SWG\Property(property="devNumber", description="设备号", type="string"),
     *              @SWG\Property(property="devType", description="设备类型(中文)", type="string"),
     *              @SWG\Property(property="mac", description="mac地址", type="string"),
     *              @SWG\Property(property="imei", description="imei号", type="string"),
     *         )
     *     ),
     *     @SWG\Response(response=200, description="认证成功",
     *         @SWG\Schema(
     *             required={"code", "msg"},
     *             @SWG\Property(property="code", description="状态码", type="integer"),
     *             @SWG\Property(property="msg", description="认证成功", type="string"),
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function identifyDemoAction()
    {
        try {
            $postData = $this->request->getJsonRawBody(true);
            $authCode = Tool::getValue($postData, 'authCode');
            $devNumber  = Tool::getValue($postData, 'devNumber');
            $devType = Tool::getValue($postData, 'devType');
            $mac = Tool::getValue($postData, 'mac');
            $imei = Tool::getValue($postData, 'imei');
            if (!$authCode || !$devNumber || !$devType) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $appInfo = XHImsApplyTablet::findFirst([
                'conditions' => 'bDelete= 0 and sAuthCode = :sAuthCode:',
                'bind'       => ['sAuthCode' => $authCode]
            ]);
            if (!$appInfo) {
                return $this->sendErrorResponse(500, '未找到申领记录,请检查授权码是否正确');
            }
            if ($appInfo->iSignState != 1 or $appInfo->iState !=3) {
                return $this->sendErrorResponse(500, '该记录未处于已领用待签收状态');
            }
            $prodInfo = XHImsProduce::findFirst([
                'columns'    => 'iProdId',
                'conditions' => 'bDelete = 0 and sProdName = :sProdName:',
                'bind'       => ['sProdName' => $devType]
            ]);
            $this->db->begin();
            if (!$prodInfo) {
                return $this->sendErrorResponse(500, '未找到设备型号');
            }
            $mTchCode = $appInfo->mTchCode;
            if (!is_array($mTchCode)) {
                $mTchCode = unserialize($mTchCode) ?: [];
            }
            if ($mTchCode) {
                if (count($mTchCode) == $appInfo->iTchNum) {
                    return $this->sendErrorResponse(500, '改申请记录已全部认证完毕');
                }
                $codeArr = array_column($mTchCode, 'code');
                if (!in_array($devNumber, $codeArr)) {
                    $mTchCode[] = ['iProdId' => $prodInfo->iProdId, 'code' => $devNumber ];
                } else {
                    return $this->sendErrorResponse(500, '已存在该设备号');
                }
//                $teachers  = explode(',', $appInfo->sTeachers);
//                foreach ($teachers as $tchId) {
//                    $mTchCode[$tchId][] = ['iProdId' => '', 'code' => ''];
//                }
//                $mTchCode[$tchId] = ['iProdId' => $prodInfo->iProdId, 'code' => $devNumber ];
            } else {
                $mTchCode[] = ['iProdId' => $prodInfo->iProdId, 'code' => $devNumber ];
            }
            $appInfo->mTchCode = $mTchCode;
            if (!$appInfo->save()) {
                throw new \Exception('认证信息保存失败');
            }
            $user = XhsysUser::findFirst([
                'columns'    => 'sUserName,sSelfPhone,sLogonName,iSchoolId',
                'conditions' => 'iUserId = :iUserId: and bDelete = 0',
                'bind'       => ['iUserId' => $appInfo->iCreateUserId]
            ]);
            if (!$user) {
                throw new \Exception('未找到该教师id对应的教师');
            }
            $checkTab = XhsysUsertablet::findFirst([
                'conditions' => ' sDevNumber = :sDevNumber: ',
                'bind'       => ['sDevNumber' => $devNumber],
                'order'      => 'iUTId desc',
            ]);
            if ($checkTab && !$checkTab->bDelete) {
                if ($checkTab->sDevNumber == $devNumber && $checkTab->sReceiverAccount == $user->sLogonName
                    && $checkTab->iReceiveStatus == 2  && $checkTab->iReceivePurpose == 0) { //已领取 教师机
                    return $this->sendSuccessResponse('认证成功');
                }
                if ($checkTab->iReceiveStatus != 3) {
                    throw new \Exception('设备号为：'.$devNumber.'的设备未归还无法申请');
                }
            }
            $tablet = new XhsysUsertablet();
            $tablet->sReceiverName    = $user->sUserName;
            $tablet->sReceiverPhone   = $user->sSelfPhone;
            $tablet->sReceiverAccount = $user->sLogonName;
            $tablet->iReceiveStatus   = 2;
            $tablet->iReceivePurpose  = 0;
            $tablet->sDevNumber       = $devNumber;
            $tablet->sDevType         = $devType;
            $tablet->bDemo            = $appInfo->bDemo;
            $tablet->iSource = 0; //自动
            if ($mac) {
                $tablet->sMacAddress = $mac;
            }
            if ($imei) {
                $tablet->sIMei = $imei;
            }
            $tablet->tReceiveTime = date('Y-m-d H:i:s', time());
            $tablet->iApTabId  = $appInfo->iRTId; //授权列表 添加 申领id
            if (!$tablet->save()) {
                throw new \Exception('记录保存失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('认证成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 保存人才信息
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190215
     */
    public function saveSourceAction()
    {
        $postData = $this->request->getJsonRawBody(true);
        $family      =  Tool::getValue($postData, 'family');
        $itemHistory =  Tool::getValue($postData, 'itemHistory');
        $tchHistory  =  Tool::getValue($postData, 'tchHistory');
        $workHistory =  Tool::getValue($postData, 'workHistory');
        $token       =  Tool::getValue($postData, 'mToken');
        if (!$postData['sStaffName'] || !$postData['sEmailAddress']) {
            return $this->sendErrorResponse(400, '名字和电子邮箱必填');
        }
        if (!$token) {
            return $this->sendErrorResponse(500, '缺少权鉴');
        }
        try {
            $this->db->begin();
            $obj = XhhrmResource::findFirst([
                'conditions' => 'bDelete = 0 and sStaffName = :sStaffName: and mToken = :mToken:  ',
                'bind'       => ['sStaffName' =>$postData['sStaffName'], 'mToken' => $token]
            ]);
            if (!$obj) {
                $obj = new XhhrmResource();
            }
            $postData = array_filter($postData);//过滤部分数据
            $obj->assign($postData);
            if (!$obj->save()) {
                throw new \Exception('基本信息保存失败');
            }
            if ($family) {
                foreach ($family as $person) {
                    $contactObj = XhhrmStaffContact::findFirst([
                        'conditions' => 'bDelete = 0 and :iSourceId: and sName = :sName:',
                        'bind'       => ['iSourceId' => $obj->iStaffId, 'sName' => $person['sName']]
                    ]);
                    if (!$contactObj) {
                        $contactObj = new XhhrmStaffContact();
                    }
                    $contactObj->assign($person);
                    $contactObj->iSourceId = $obj->iStaffId;
                    if (!$contactObj->save()) {
                        throw new \Exception('主要家庭成员保存失败');
                    }
                }
            }
            if ($itemHistory) {
                foreach ($itemHistory as $item) {
                    $itemObj = XhhrmExperience::findFirst([
                        'conditions' => 'bDelete = 0 and :iSourceId: and sName = :sName: and sTag = :sTag: ',
                        'bind'       => ['iSourceId' => $obj->iStaffId, 'sName' => $item['sName'], 'sTag' => 'item']
                    ]);
                    if (!$itemObj) {
                        $itemObj = new XhhrmExperience();
                    }
                    $itemObj->assign($item);
                    $itemObj->iSourceId = $obj->iStaffId;
                    $itemObj->sTag = strtolower('item');
                    if (!$itemObj->save()) {
                        throw new \Exception('项目信息保存失败');
                    }
                }
            }
            if ($tchHistory) {
                foreach ($tchHistory as $tch) {
                    $tchObj = XhhrmExperience::findFirst([
                        'conditions' => 'bDelete = 0 and :iSourceId: and sName = :sName: and sTag = :sTag: ',
                        'bind'       => ['iSourceId' => $obj->iStaffId, 'sName' => $tch['sName'], 'sTag' => 'lean']
                    ]);
                    if (!$tchObj) {
                        $tchObj = new XhhrmExperience();
                    }
                    $tchObj->assign($tch);
                    $tchObj->iSourceId = $obj->iStaffId;
                    $tchObj->sTag = strtolower('lean');
                    if (!$tchObj->save()) {
                        throw new \Exception('学习经历保存失败');
                    }
                }
            }
            if ($workHistory) {
                foreach ($workHistory as $work) {
                    $workObj = XhhrmExperience::findFirst([
                        'conditions' => 'bDelete = 0 and :iSourceId: and sName = :sName: and sTag = :sTag: ',
                        'bind'       => ['iSourceId' => $obj->iStaffId, 'sName' => $work['sName'], 'sTag' => 'work']
                    ]);
                    if (!$workObj) {
                        $workObj = new XhhrmExperience();
                    }
                    $workObj->assign($work);
                    $workObj->iSourceId = $obj->iStaffId;
                    $workObj->sTag = strtolower('work');
                    if (!$workObj->save()) {
                        throw new \Exception('工作经历保存失败');
                    }
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage()
            );
        }
    }

}

/**
 * @SWG\Definition(
 *     definition="UserInfo",
 *     @SWG\Property(property="userId", description="用户id", type="string"),
 *     @SWG\Property(property="userName", description="姓名", type="string"),
 *     @SWG\Property(property="logonName", description="登陆名", type="string"),
 *     @SWG\Property(property="adClaName", description="行政班", type="string"),
 *     @SWG\Property(property="phoneNum", description="电话", type="string"),
 *     @SWG\Property(property="schoolId", description="学校id", type="string"),
 *     @SWG\Property(property="schoolName", description="学校名称", type="string"),
 * )
 */

